package com.study.examples.common.convert;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * @ClassName: BeanConvertHelper
 * @Description: Bean 转换
 * @author: limingxing
 * @Date: 2020-06-04 17:19
 */
public class BeanConvertHelper {

    /**
     * usage:
     * Person po = new Person();
     * PersonDTO dto = convert(po, PersonDTO::new);
     *
     * @param d
     * @param supplier
     * @param <D>
     * @param <T>
     * @return
     */
    public static <D, T> T convert(D d, Supplier<T> supplier) {
        if (d == null) {
            return null;
        }
        T t = supplier.get();
        BeanUtils.copyProperties(d, t);
        return t;
    }

    public static <D, T> List<T> convert(List<D> dl, Supplier<T> supplier) {
        if (dl == null) {
            return null;
        }
        List<T> tl = new ArrayList<>(dl.size());
        dl.forEach(d -> tl.add(convert(d, supplier)));
        return tl;
    }

    public static <D, T> IPage<T> convert(IPage<D> dp, Supplier<T> supplier) {
        if (dp == null) {
            return null;
        }
        Page<T> tp = new Page<>(dp.getCurrent(), dp.getSize());
        tp.setTotal(dp.getTotal());
        tp.setRecords(new ArrayList<>(dp.getRecords().size()));
        dp.getRecords().forEach(d -> tp.getRecords().add(convert(d, supplier)));
        return tp;
    }

    public static <T> IPage<T> from(IPage<?> source) {
        IPage<T> r = new Page<>(source.getCurrent(), source.getSize());
        r.setPages(source.getPages());
        r.setTotal(source.getTotal());
        if (source.getRecords() != null) {
            r.setRecords(new ArrayList<>(source.getRecords().size()));
        }
        return r;
    }

}
